<template>
  <div class="jnpf-content-wrapper">
    <div class="jnpf-content-wrapper-center">
      <div class="jnpf-content-wrapper-search-box" style="padding-bottom: 12px; display: flex">
        <div class="input-container">
          <label class="label" for="inputField">公司名称:</label>
          <a-input id="inputField" v-model:value="proCompany" placeholder="请输入" />
          <label class="label" for="inputField">联系人:</label>
          <a-input id="inputField" v-model:value="proName" placeholder="请输入" />
        </div>
        <div class="button">
          <a-button @click="reset">重置</a-button>
          <a-button type="primary" style="margin-left: 10px" @click="init">查询</a-button>
        </div>
      </div>
      <div class="jnpf-content-wrapper-content">
        <div class="table-header">
          <span class="header-title">招投标代理服务机构</span>
          <a-button type="primary" :icon="h(PlusOutlined)" @click="toAdd">新建</a-button>
        </div>
        <a-table
          :columns="columns"
          :loading="tableLoading"
          :data-source="dataList"
          :pagination="paginationProp"
          :scroll="{ x: 1500, y: 410 }"
          :style="{ height: 'calc(100vh - 280px)' }">
          <template #bodyCell="{ column, record, text }">
            <template v-if="column.key === 'status'">
              <span class="custom-cell">
                <span :class="text == 1 ? 'dcq-dot' : 'ycq-dot'"></span>
                {{ text == 1 ? '无效' : '有效' }}
              </span>
            </template>
            <template v-if="column.key === 'operation'">
              <div class="button-container">
                <a-button type="link" class="operation-button" @click="toView(record)">查看</a-button>
                <a-button type="link" class="operation-button" @click="toEdit(record)">编辑</a-button>
                <a-button type="link" danger class="operation-button" @click="toDel(record)">删除</a-button>
              </div>
            </template>
          </template>
        </a-table>
      </div>
    </div>
    <!-- 新增弹窗 -->
    <a-modal v-model:visible="open" :title="addTitle" centered :maskClosable="false" :keyboard="false" :width="800" @ok="handleOk">
      <a-form ref="formRef" :model="formSchemas" name="tree-node" :rules="rules" autocomplete="off" :label-col="{ style: { width: '120px' } }" :colon="false">
        <a-row :gutter="16" style="margin-top: 15px">
          <a-col class="gutter-row" :span="24">
            <a-form-item label="公司编号">
              <a-input :disabled="true" style="width: 90%" v-model:value="formSchemas.proNumber" placeholder="保存后系统自动生成" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col class="gutter-row" :span="24">
            <a-form-item label="公司名称" name="proName">
              <a-input v-model:value="formSchemas.proName" style="width: 90%" :disabled="addTitle == '查看公司'" placeholder="请输入" />
            </a-form-item>
          </a-col>
        </a-row>
        <div v-for="(contact, index) in formSchemas.contacts" :key="index" style="display: flex; padding-right: 20px">
          <a-form-item :label="'联系人 ' + (index == 0 ? '' : index + 1) + '：'" :name="'proPeople' + index">
            <a-input v-model:value="contact.contactName" :disabled="addTitle == '查看公司'" placeholder="请输入" />
          </a-form-item>
          <a-form-item :label="'联系方式：'" :name="'proTel' + index">
            <a-input-number v-model:value="contact.contactPhone" :controls="false" :disabled="addTitle == '查看公司'" placeholder="请输入" />
          </a-form-item>
          <div class="btn_containers">
            <a-button v-if="index == 0 && addTitle != '查看公司'" type="primary" @click="addPeople">添加联系人</a-button>
            <DeleteOutlined class="icon" @click="deletePeople(index)" v-if="index != 0 && addTitle != '查看公司'" style="font-size: 20px; margin-top: 10px" />
          </div>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, h, reactive, onMounted, toRefs } from 'vue';
  import { getList, dictionaryData, addZjList, addDictionary, editDictionary, deleteDictionary, editList, deleteList, queryInfo } from './helper/api';
  import { buildBitUUID } from '/@/utils/uuid';
  import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import { Modal as AModal } from 'ant-design-vue';
  import type { FormInstance } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { forEach } from '../../../utils/helper/treeHelper';
  const { createConfirm, createMessage } = useMessage();

  const formRef = ref<FormInstance>(); //新增弹窗dom
  const proName = ref<string>(''); //联系人
  const tableLoading = ref<boolean>(false); //列表loading
  const proCompany = ref<string>(''); //公司名称
  const open = ref<boolean>(false); //新增弹窗
  const addTitle = ref<string>('新增公司'); //新增弹窗标题
  //分页相关
  const page = ref(1);
  const pageSize = ref(10);
  const total = ref(0);
  const paginationProp = ref({
    showSizeChanger: false,
    showQuickJumper: true,
    pageSize,
    current: page,
    total,
    showTotal: total => `总 ${total} 条`,
    onChange: pageChange,
    onShowSizeChange: pageSizeChange,
  });
  function pageChange(p, pz) {
    page.value = p;
    pageSize.value = pz;
    init();
  }
  function pageSizeChange(_current, size) {
    pageSize.value = size;
    init();
  }
  const state = reactive({
    formSchemas: {
      id: '',
      proName: '', //公司名称
      proNumber: '', //公司编号
      proPeople: '', //联系人
      proTel: '', //联系方式
      contacts: [
        { contactName: '', contactPhone: '' }, // 初始联系人项
      ],
    },
  });
  const { formSchemas } = toRefs(state);
  // 新增弹窗校验
  const rules = {
    proName: [{ required: true, message: '必填' }],
    proNumber: [{ required: true, message: '必填' }],
    proPeople: [{ required: true, message: '必填' }],
    proTel: [{ required: true, message: '必填' }],
  };
  // 分页列表
  const columns = [
    { title: '序号', width: 70, customRender: ({ index }) => index + 1, key: 'name', align: 'center' },
    { title: '公司编号', dataIndex: 'id', width: 150, key: 'id', align: 'center' },
    { title: '招投标公司', dataIndex: 'companyName', key: 'companyName', width: 350, align: 'center' },
    { title: '联系人', dataIndex: 'contactNames', key: 'contactNames', width: 200, align: 'center' },
    { title: '联系方式', dataIndex: 'contactPhones', key: 'contactPhones', width: 300, align: 'center' },
    { title: '状态', dataIndex: 'status', key: 'status', align: 'center' },
    {
      title: '操作',
      key: 'operation',
      align: 'center',
      fixed: 'right',
      width: 180,
    },
  ];
  const dataList = ref<any[]>([]); //分页数组
  for (let i = 0; i < 100; i++) {
    dataList.value.push({
      key: i,
      name: `Edrward ${i}`,
      age: 32,
      address: `London Park no. ${i}`,
    });
  }
  onMounted(() => {
    init();
  });
  const processData = data => {
    return data.map(item => {
      // 提取 contactInformation
      const contactInformation = item.contactInformation || [];

      // 分别提取 contactName 和 contactPhone
      const contactNames = contactInformation.map(contact => contact.contactName);
      const contactPhones = contactInformation.map(contact => contact.contactPhone);

      // 返回新的数据结构
      return {
        ...item,
        // contactInformation: undefined, // 移除原来的 contactInformation
        contactNames: contactNames,
        contactPhones: contactPhones,
      };
    });
  };
  // 初始化数据
  const init = () => {
    tableLoading.value = true;
    getList({
      dataType: 2,
      pageNum: page.value,
      pageSize: pageSize.value,
      companyName: proCompany.value,
      concatPerson: proName.value, //联系人
    }).then(res => {
      res.data.records = processData(res.data.records);
      res.data.records.forEach(v => {
        v.contactNames = v.contactNames.join('，');
        v.contactPhones = v.contactPhones.join('，');
      });
      total.value = res.data.total;
      dataList.value = res.data.records;
      tableLoading.value = false;
      console.log('dataList.value', dataList.value);
    });
  };
  //重置数据
  const reset = () => {
    proName.value = '';
    proCompany.value = '';
    init();
  };
  //添加
  const toAdd = () => {
    state.formSchemas = {
      proName: '', //公司名称
      proNumber: '', //公司编号
      proPeople: '', //联系人
      proTel: '', //联系方式
      contacts: [
        { contactName: '', contactPhone: '' }, // 初始联系人项
      ],
    };
    addTitle.value = '新增公司';
    open.value = true;
  };
  //查看
  const toView = v => {
    open.value = true;
    addTitle.value = '查看公司';
    queryInfo({
      id: v.id,
    }).then(res => {
      console.log('res', res);
      let data = res.data;
      state.formSchemas = {
        proName: data.companyName, //公司名称
        proNumber: data.id, //公司编号
        proPeople: data.createName, //联系人
        proTel: data.phoneNumber, //联系方式
        contacts: data.contactInformation, // 初始联系人项
        id: '',
      };
    });
  };
  //编辑
  const toEdit = v => {
    open.value = true;
    addTitle.value = '编辑公司';
    state.formSchemas = {
      proName: v.companyName, //公司名称
      proNumber: v.id, //公司编号
      proPeople: v.createName, //联系人
      proTel: v.phoneNumber, //联系方式
      contacts: v.contactInformation, // 初始联系人项
      id: v.id,
    };
    console.log('toEdit', v);
  };
  // 删除
  const toDel = v => {
    createConfirm({
      iconType: 'warning',
      title: '温馨提示',
      content: `请确认是否要删除该条数据,删除后则该条数据不再显示。`,
      onOk: () => {
        deleteList({
          id: v.id,
        }).then(res => {
          console.log('res', res);
          createMessage.success('操作成功!');
          init();
        });
      },
    });
    console.log('toDel', v);
  };
  //确认新建弹窗
  const handleOk = async () => {
    try {
      const values = await formRef.value?.validate();
      const hasEmptyField = state.formSchemas.contacts.some(contact => !contact.contactName || !contact.contactPhone);
      if (hasEmptyField) {
        return createMessage.error('联系人姓名和联系方式不能为空');
      }
      if (values) {
        if (addTitle.value == '新增公司') {
          addZjList({
            dataType: '2', //新增类型 1-专家 2-公司 默认专家
            companyName: state.formSchemas.proName, //公司名称(招投标类型)
            contactInformation: state.formSchemas.contacts,
          }).then(res => {
            console.log('res', res);
            createMessage.success('创建成功!');
            init();
            open.value = false;
          });
        } else {
          editList({
            dataType: '2', //新增类型 1-专家 2-公司 默认专家
            companyName: state.formSchemas.proName, //公司名称(招投标类型)
            contactInformation: state.formSchemas.contacts,
            id: state.formSchemas.id, //专家编号
          }).then(res => {
            console.log('res', res);
            createMessage.success('编辑成功!');
            init();
            open.value = false;
          });
        }
        open.value = false;
      }
    } catch (_) {}
  };
  //添加联系人
  const addPeople = () => {
    state.formSchemas.contacts.push({ contactName: '', contactPhone: '' });
  };
  // 删除联系人
  const deletePeople = index => {
    // 从 contacts 数组中移除指定索引的联系人项
    state.formSchemas.contacts.splice(index, 1);
  };
</script>
<style lang="less" scoped>
  .input-container {
    display: flex;
    align-items: center; /* 垂直居中对齐 */
    gap: 10px; /* 标签和输入框之间的间距 */
  }

  .label {
    width: 170px; /* 设置标签宽度 */
  }
  a-input {
    flex: 1; /* 使输入框在容器中尽可能扩展 */
    margin: 0 5px; /* 输入框左右的间距 */
  }
  .button {
    position: absolute;
    right: 10px;
  }
  .button-container {
    display: flex;
    flex-wrap: wrap; /* 允许按钮换行 */
    justify-content: flex-start; /* 按钮对齐方式，根据需要可以调整 */
  }

  .operation-button {
    white-space: nowrap; /* 防止按钮文本换行 */
  }
  .ant-table-tbody > tr > td {
    padding: 0;
  }
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fafafa;
    padding: 10px 10px 0px 10px; /* Space between header and table */
  }

  .header-title {
    font-weight: bold;
    font-size: 18px; /* Adjust font size as needed */
  }
  .btn_containers {
    width: 100px;
    height: 33px;
    line-height: 33px;
    text-align: center;
    margin-left: 20px;
    margin-top: 10px;
  }
  :deep(.ant-table-tbody > tr > td) {
    padding: 0 !important;
  }
  .custom-cell {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .dcq-dot {
    width: 4px;
    height: 4px;
    background-color: #ff8d23; /* Change the color as needed */
    border-radius: 50%;
    margin-right: 8px;
  }
  .ycq-dot {
    width: 4px;
    height: 4px;
    background-color: #52c41a; /* Change the color as needed */
    border-radius: 50%;
    margin-right: 8px;
  }
  // :deep(.ant-table-tbody) {
  //   height: 400px;
  // }
  :deep(.jnpf-content-wrapper-content .ant-table-empty .ant-table-tbody > tr.ant-table-placeholder) {
    height: 400px;
  }
  :deep(.ant-table-thead > tr > th) {
    color: rgba(0, 0, 0, 0.85);
    font-weight: 600;
    background: #fafafa;
    border-bottom: 1px solid #f0f0f0;
    transition: background 0.3s ease;
  }
  :deep(.ant-table-tbody > tr > td) {
    color: rgba(0, 0, 0, 0.85);
    background: #fafafa;
    border-bottom: 1px solid #f0f0f0;
  }
</style>
